#define _CRT_SECURE_NO_WARNINGS 1

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution
{
public:
    ListNode* reverse(ListNode* head)
    {
        ListNode* newHead = new ListNode(0);
        ListNode* cur = head;

        while (cur)
        {
            ListNode* next = cur->next;
            cur->next = newHead->next;
            newHead->next = cur;
            cur = next;
        }
        cur = newHead->next;
        delete newHead;
        return cur;
    }

    ListNode* addInList(ListNode* h1, ListNode* h2)
    {
        h1 = reverse(h1);
        h2 = reverse(h2);

        int t = 0;
        ListNode* cur1 = h1;
        ListNode* cur2 = h2;

        ListNode* ret = new ListNode(0);
        ListNode* prev = ret;

        while (cur1 || cur2 || t)
        {
            if (cur1)
            {
                t += cur1->val;
                cur1 = cur1->next;
            }
            if (cur2)
            {
                t += cur2->val;
                cur2 = cur2->next;
            }
            prev = prev->next = new ListNode(t % 10);
            t /= 10;
        }
        ListNode* newHead = ret->next;
        delete ret;
        return reverse(newHead);
    }
};